package com.atguigu.flink.chapter07.state;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.AggregatingState;
import org.apache.flink.api.common.state.AggregatingStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/12/15 9:26
 */
public class Flink07_Keyed_State_Aggregate {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 20000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env
            .socketTextStream("hadoop162", 9999)
            .map(line -> {
                String[] data = line.split(",");
                return new WaterSensor(data[0], Long.valueOf(data[1]), Integer.valueOf(data[2]));
            })
            .keyBy(WaterSensor::getId)
            .process(new KeyedProcessFunction<String, WaterSensor, String>() {
                
                private AggregatingState<WaterSensor, Double> vcAvgState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    vcAvgState = getRuntimeContext().getAggregatingState(new AggregatingStateDescriptor<WaterSensor, MyAvg, Double>(
                        "vcAvgState",
                        new AggregateFunction<WaterSensor, MyAvg, Double>() {
                            @Override
                            public MyAvg createAccumulator() {
                                return new MyAvg();
                            }
                            
                            @Override
                            public MyAvg add(WaterSensor value, MyAvg acc) {
                                acc.sum += value.getVc();
                                acc.count++;
                                return acc;
                            }
                            
                            @Override
                            public Double getResult(MyAvg acc) {
                                return acc.avg();
                            }
                            
                            @Override
                            public MyAvg merge(MyAvg a, MyAvg b) {
                                return null;
                            }
                        },
                        MyAvg.class)
                    );
                }
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    vcAvgState.add(value);
                    
                    out.collect(ctx.getCurrentKey() + " " + vcAvgState.get());
                }
            })
            .print();
        
        env.execute();
    }
    
    public static class MyAvg {
        public Integer sum = 0;
        public Long count = 0L;
        
        public Double avg() {
            return sum * 1.0 / count;
        }
    }
    
}
